﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace MLY.Bll
{
  public class OrganizationShort
  {
    private Dal.TableOrganization m_tableOrganization;

    public OrganizationShort()
    {
      totalSum = 0;
      countMe = 0;
      m_tableOrganization = new MLY.Dal.TableOrganization();
    }

    public int countMe { get; set; }

    public float totalSum { get; set; }

    public int OrganizationId
    {
      get
      {
        return m_tableOrganization.OrganizationId;
      }
    }

    // The property ContactPersonEmail used in OrganizationShortComparer.Compare() to sort "Contact Person's Email" in
    // Client-->Suppliers grid. Without it there is run time exception.
    public string ContactPersonEmail { get { return m_tableOrganization.ContactPersonEmail; } }
    public string OrganizationEmail { get { return m_tableOrganization.ContactPersonEmail; } }
    public string OrganizationName { get { return m_tableOrganization.OrganizationName; } }
    public string ContactPerson { get { return m_tableOrganization.ContactPerson; } }
    public string WebSite { get { return m_tableOrganization.WebSite; } }
    private static void CalcTotal(OrganizationShort og, Dal.TableWorkOrder n)
    {
      og.countMe++;
      Nullable<decimal> quantity = n.Quantity;                                              // 13/03/11
      if (quantity != null)
        og.totalSum += (float)quantity.Value;
    }

    public static List<OrganizationShort> GetOrganizationShortByClientId(int clientId, string p_sortExpression, string p_sortDirection)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext(g.AppConnectionString))
      {
        List<OrganizationShort> retval = new List<OrganizationShort>();
        List<Dal.TableWorkOrder> workOrders = (from p in db.TableWorkOrders
                                               where p.CustomerId == clientId &&
                                                       p.ActualDelivaryDate == null
                                               select p).ToList();
        List<Dal.TableOrganization> contractors = (from p in db.TableOrganizationRelations
                                                   join q in db.TableOrganizations on p.ContractorId equals q.OrganizationId
                                                   where p.CustomerId == clientId select q).ToList();
        foreach (Dal.TableOrganization contractor in contractors)
        {
          OrganizationShort og = new OrganizationShort();
          og.m_tableOrganization = contractor;
          foreach (Dal.TableWorkOrder workOrder in workOrders)
          {
            if (contractor.OrganizationId == workOrder.ContractorId)
              CalcTotal(og, workOrder);
          }
          retval.Add(og);
        }

        SortOrganizationShort(p_sortExpression, p_sortDirection, retval);
        return retval;
      }
    }

    private static void SortOrganizationShort(string p_sortExpression, string p_sortDirection, List<OrganizationShort> retval)
    {
      if (p_sortExpression != null && p_sortExpression != string.Empty)
        retval.Sort(new OrganizationShortComparer(p_sortExpression));

      // Now that we have sorted check to see if the sort direction is desc
      if (p_sortDirection != null && p_sortDirection == "Desc")
        retval.Reverse();
    }

    public static List<OrganizationShort> GetOrganizationShortByContractorId(int contractorId, string p_sortExpression, string p_sortDirection)
    {
      using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext(g.AppConnectionString))
      {
        List<OrganizationShort> retval = new List<OrganizationShort>();
        List<Dal.TableWorkOrder> workOrders = (from p in db.TableWorkOrders
                                               where p.ContractorId == contractorId &&
                                                     p.ActualDelivaryDate == null
                                               select p).ToList();
        List<Dal.TableOrganization> clients = (from p in db.TableOrganizationRelations
                                               join q in db.TableOrganizations on
                                                    p.CustomerId equals q.OrganizationId
                                               where p.ContractorId == contractorId
                                               select q).ToList();
        foreach (Dal.TableOrganization client in clients)
        {
          OrganizationShort og = new OrganizationShort();
          og.m_tableOrganization = client;
          foreach (Dal.TableWorkOrder workOrder in workOrders)
            if (client.OrganizationId == workOrder.CustomerId)
              CalcTotal(og, workOrder);
          retval.Add(og);
        }

        SortOrganizationShort(p_sortExpression, p_sortDirection, retval);
        return retval;
      }
    }
  }
    
  class OrganizationShortComparer : IComparer<OrganizationShort>
  {
    string PropertyName = "";

    public OrganizationShortComparer(string prop_name)
    {
      PropertyName = prop_name;
    }

    #region IComparer<OrganizationShort> Members
    
    public int Compare(OrganizationShort x, OrganizationShort y)
    {
      Type t = x.GetType();
      PropertyInfo val = t.GetProperty(this.PropertyName);
      if (val != null)
      {
        return Comparer.DefaultInvariant.Compare(val.GetValue(x, null), val.GetValue(y, null));
      }
      else
      {
        throw new Exception(this.PropertyName + " is not a valid property to sort on.  It doesn't exist in the Class.");
      }
    }

    #endregion IComparer<OrganizationShort> Members
  }
}
